package DAOHibernate;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import acceso.EMF;

import modelo.PalabraClave;
import DAO.PalabraClaveDAO;

public class PalabraClaveDAOhiberjpa implements PalabraClaveDAO {

	private static EntityManagerFactory emf = Persistence
			.createEntityManagerFactory("base-ttps-final");

	@Override
	public void agregarPalabraClave(PalabraClave palabraClave) {
		// TODO Auto-generated method stub
		EntityManager em = PalabraClaveDAOhiberjpa.emf.createEntityManager();
		EntityTransaction etx = em.getTransaction();
		etx.begin();
		em.persist(palabraClave);
		em.flush();
		etx.commit();
		em.close();
	}

	public String buscarPalabrasClavesPorIdTesis(Long idTesis){
		
		
		EntityManager em = EMF.getEMF().createEntityManager();
		EntityTransaction etx = em.getTransaction();
		etx.begin();

		@SuppressWarnings("unchecked")
		List<PalabraClave> palabraClaves = (List<PalabraClave>) (em
				.createQuery("from PalabraClave where tesina.id = " + idTesis + ""))
				.getResultList();
		
		StringBuffer palabrasC = new StringBuffer ("");
		boolean primera = true;
		
		for (PalabraClave pal : palabraClaves) {
			if (primera){
				palabrasC.append(pal.getPalabra());
				primera = false;
			}else{
				palabrasC.append(",");
				palabrasC.append(pal.getPalabra());
			}
			
		}
		em.close();
		etx.commit();
		
		
		
		return palabrasC.toString();
	}
	
}
